package com.zhaojk.audio.mapper.handler;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zhaojk.audio.entity.TemplateVariable;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedTypes;
import org.postgresql.util.PGobject;

import java.sql.*;
import java.util.Collections;
import java.util.List;

/**
 *
 */
@MappedTypes(List.class)
public class PgJsonbTypeHandler extends BaseTypeHandler<List<TemplateVariable>> {
    private static final ObjectMapper objectMapper = new ObjectMapper();
    private static final TypeReference<List<TemplateVariable>> TYPE_REFERENCE =
            new TypeReference<List<TemplateVariable>>() {};

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i,
                                    List<TemplateVariable> parameter, JdbcType jdbcType)
            throws SQLException {
        PGobject jsonObject = createPGobject();
        try {
            jsonObject.setValue(objectMapper.writeValueAsString(parameter));
            ps.setObject(i, jsonObject);
        } catch (Exception e) {
            throw new SQLException("Failed to serialize JSON", e);
        }
    }

    @Override
    public List<TemplateVariable> getNullableResult(ResultSet rs, String columnName)
            throws SQLException {
        return parseJson(rs.getString(columnName));
    }

    @Override
    public List<TemplateVariable> getNullableResult(ResultSet rs, int columnIndex)
            throws SQLException {
        return parseJson(rs.getString(columnIndex));
    }

    @Override
    public List<TemplateVariable> getNullableResult(CallableStatement cs, int columnIndex)
            throws SQLException {
        return parseJson(cs.getString(columnIndex));
    }

    private List<TemplateVariable> parseJson(String json) {
        try {
            if (json == null || json.trim().isEmpty()) {
                return Collections.emptyList();
            }
            return objectMapper.readValue(json, TYPE_REFERENCE);
        } catch (Exception e) {
            throw new RuntimeException("Failed to parse JSON: " + abbreviate(json, 100), e);
        }
    }

    private PGobject createPGobject() throws SQLException {
        PGobject obj = new PGobject();
        obj.setType("jsonb");
        return obj;
    }

    private String abbreviate(String str, int maxWidth) {
        if (str == null) {
            return "null";
        }
        return str.length() <= maxWidth ? str : str.substring(0, maxWidth) + "...";
    }
}